/*jslint node:true nomen:true*/
'use strict';
var express = require('express');
var app = express();
var fs = require('fs');

var user = {
    "user4" : {
        "name" : "mohit",
        "password" : "password4",
        "profession" : "teacher",
        "id": 4
    }
};

app.get('/listUsers', function (req, res) {
    fs.readFile(__dirname + '/' + 'users.json', 'utf8', function (err, data) {
        console.log(data.toString());
        res.end(data);
    });
});

app.get('/addUser', function (req, res) {
    fs.readFile(__dirname + '/' + 'users.json', 'utf8', function (err, data) {
        data = JSON.parse(data);
        data.user4 = user.user4;
        console.log(JSON.stringify(data));
        res.end(JSON.stringify(data));
    });
});

app.get('/deleteUser', function (req, res) {
    fs.readFile(__dirname + '/' + 'users.json', 'utf8', function (err, data) {
        data = JSON.parse(data);
        delete data['user' + 2];
        console.log(data);
        res.end(JSON.stringify(data));
    });
});

app.get('/:id', function (req, res) {// '/:id'这个api如果放在前面，那么放在这个后面的都不能用，不知道为何
    fs.readFile(__dirname + '/' + 'users.json', 'utf8', function (err, data) {
        data = JSON.parse(data);
        var user = data['user' + req.params.id]; //运行失败主要跟这句有关，使用了得不到的值，放在前面估计是优先匹配到这个，至于这个:id为什么能匹配到前面的，未明
        console.log(data);
        res.end(JSON.stringify(data));
    });
});

var server = app.listen(8888, function () {
    var host = server.address().address,
        port = server.address().port;
    console.log('应用实例，访问地址为 http://%s:%s', host, port);
});